package org.qianji.goosql.field;

import org.qianji.goosql.table.Table;

/**
 * 表字段，指定表的字段。
 * 
 * @author gmz
 * 
 */
public class TableField extends SimpleField {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4893487488437316439L;

	private Table table;

	/**
	 * 根据表、字段名构造表字段。
	 * 
	 * @param table
	 *            {@link Table Table} 表
	 * @param fieldName
	 *            {@link String String} 字段名
	 */
	public TableField(Table table, String fieldName) {
		super(fieldName);
		if (table == null) {
			throw new NullPointerException("table can't be null");
		}
		this.table = table;
	}

	/**
	 * 获取表。
	 * 
	 * @return {@link Table Table} 表
	 */
	public Table getTable() {
		return table;
	}

	@Override
	public String toSql() {
		StringBuffer fld = new StringBuffer(table.getTableName()).append(".").append(getFieldName());
		return fld.toString();
	}

	@Override
	public String getField() {
		return toSql();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null || !(obj instanceof TableField)) {
			return false;
		}
		TableField other = (TableField) obj;
		if (getFieldName().equals(other.getFieldName()) && table.equals(other.getTable())) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int hc = 37 * 17 + getFieldName().hashCode();
		hc = 37 * hc + table.hashCode();
		return hc;
	}

	@Override
	public String toString() {
		return toSql();
	}

}
